package edu.fpa.day0806;

public class SynCinema {
    public static void main(String[] args) {
        Cinema cinema = new Cinema(100,"影院");
        Customer customer1 = new Customer(cinema,20,"a");
        Customer customer2 = new Customer(cinema,40,"b");
        Customer customer3 = new Customer(cinema,30,"c");
        Customer customer4 = new Customer(cinema,50,"d");
        customer1.start();
        customer2.start();
        customer3.start();
        customer4.start();

    }
}
class Cinema{
    int available;
    String name;
    public Cinema(int available, String name) {
        super();
        this.available = available;
        this.name = name;
    }
    public boolean buyticket(int seat) {
        System.out.println("可用位置为："+available);
        if(available>=seat) {
            available -= seat;
            return true;
        }else {
            return false;
        }
    }
}

class Customer extends Thread{

    Cinema cinema;
    int seats;
    boolean flag;

    public Customer(Cinema cinema, int seats,String name) {
        super(name);
        this.cinema = cinema;
        this.seats = seats;
    }

    @Override
    public void run() {
        synchronized (cinema){
            flag = cinema.buyticket(seats);
            if(flag) {
                System.out.println(Thread.currentThread().getName()+"->购票成功"+seats+"张");
            }
            else {
                System.out.println(Thread.currentThread().getName()+"->购票失败");
            }
        }
    }

}